package nicg.st.service;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Service;

import nicg.st.dao.EvalDataEnterMapper;
import nicg.st.dao.ResultMapper;
import nicg.st.entity.Bar;
import nicg.st.entity.EvalResult;
import nicg.st.entity.IndicatorDataDetail;
import nicg.st.entity.IndicatorDetail;
import nicg.st.entity.MyConfig;
import nicg.st.entity.PieVO;
import nicg.st.entity.Radar;
import nicg.st.entity.ResultList;
import nicg.st.entity.SchemeList;
import nicg.st.exception.GlobalException;
import nicg.st.outerAPI.OuterInfo;
import nicg.st.outerAPI.bean.GetTreeNodesBean;
import nicg.st.util.ErrorCode;
import nicg.st.util.ResponseUtil;

/**
 * @author GeChen
 * @Description
 * @date 2019/11/3 23:30
 */
@Service
public class ResultService {
	@Resource
	ResultMapper resultMapper;
	@Resource
	EvalDataEnterMapper evalDataEnterMapper;
	@Resource
	MyConfig myConfig;

	private Map<String, String> divateMap = new HashMap<>();
	private Map<String, String> solveMap = new HashMap<>();

	/**
	 * 得到动态名录的list信息
	 * 
	 * @param type
	 * @return
	 */
	public String getTreeNodes(String type) {
		GetTreeNodesBean data = OuterInfo.getDTMLTreeNodes(myConfig.getDtmlServerIp(), myConfig.getDtmlServerPort(),
				myConfig.getDtmlGetTreeNodes());
		if (data == null) {
			throw new GlobalException("获取动态名录失败");
		} else {
			return ResponseUtil.getResponseString(ErrorCode.SUCCESSFUL, "获取动态名录失败", data);
		}
	}

	public List<SchemeList> findScheme() {
		List<SchemeList> list = resultMapper.findScheme();
		for (int i = 0; i < list.size(); i++) {
			String name = list.get(i).getName();
			list.get(i).setName(name.substring(0, name.lastIndexOf("+")));
		}
		return list;
	}

	public int findSchemeSum() {
		return resultMapper.findSchemeSum();
	}

	public int findSchemeSearchSum(String startTime, String endTime) {
		return resultMapper.findSchemeSearchSum(startTime, endTime);
	}

	public int findSchemeSearchNameSum(String searchName) {
		return resultMapper.findSchemeSearchNameSum(searchName);
	}

	public int findSchemeSearchAllSum(String startTime, String endTime, String searchName) {
		return resultMapper.findSchemeSearchAllSum(startTime, endTime, searchName);
	}

	public List<ResultList> findSchemeByPage(int page) {
		// 每页显示信息数量
		int pageSize = 10;
		int offset = (page - 1) * pageSize;
		List<SchemeList> list = resultMapper.findSchemeByPage(offset, pageSize);
		List<ResultList> resList = new ArrayList<ResultList>();
		for (int i = 0; i < list.size(); i++) {
			String name = list.get(i).getName();
			list.get(i).setName(name.substring(0, name.lastIndexOf("+")));
			ResultList res = new ResultList();
			res.setId(list.get(i).getId());
			res.setName(list.get(i).getName());
			String indicatorName = resultMapper.selectIndicatorNameId(list.get(i).getIndicatorId());
			res.setIndicatorName(indicatorName);
			res.setUserId(list.get(i).getUserId());
			res.setDate(list.get(i).getDate());
			res.setScore(list.get(i).getScore());
			res.setReport(list.get(i).getReport());
			res.setRemark(list.get(i).getRemark());
			resList.add(res);
		}
		return resList;
	}

	public List<SchemeList> findSchemeSearchByPage(int page, String startTime, String endTime) {
		// 每页显示信息数量
		int pageSize = 10;
		int offset = (page - 1) * pageSize;
		List<SchemeList> list = resultMapper.findSchemeSearchByPage(startTime, endTime, offset, pageSize);
		for (int i = 0; i < list.size(); i++) {
			String name = list.get(i).getName();
			list.get(i).setName(name.substring(0, name.lastIndexOf("+")));
		}
		return list;
	}

	public List<SchemeList> findSchemeSearchNameByPage(int page, String searchName) {
		// 每页显示信息数量
		int pageSize = 10;
		int offset = (page - 1) * pageSize;
		List<SchemeList> list = resultMapper.findSchemeSearchNameByPage(searchName, offset, pageSize);
		for (int i = 0; i < list.size(); i++) {
			String name = list.get(i).getName();
			list.get(i).setName(name.substring(0, name.lastIndexOf("+")));
		}
		return list;
	}

	public List<ResultList> findSchemeSearchAllByPage(int page, String startTime, String endTime, String searchName) {
		// 每页显示信息数量
		int pageSize = 10;
		int offset = (page - 1) * pageSize;
		List<SchemeList> list = resultMapper.findSchemeSearchAllByPage(startTime, endTime, searchName, offset,
				pageSize);
		List<ResultList> resList = new ArrayList<ResultList>();
		for (int i = 0; i < list.size(); i++) {
			String name = list.get(i).getName();
			list.get(i).setName(name.substring(0, name.lastIndexOf("+")));
			ResultList res = new ResultList();
			res.setId(list.get(i).getId());
			res.setName(list.get(i).getName());
			System.out.println("list.indicatorId=" + list.get(i).getIndicatorId());
//        	String indicatorName=resultMapper.selectIndicatorPathBySchemeId(list.get(i).getId());
			String indicatorName = resultMapper.selectIndicatorNameId(list.get(i).getIndicatorId());
			res.setIndicatorName(indicatorName);
			res.setUserId(list.get(i).getUserId());
			res.setDate(list.get(i).getDate());
			res.setScore(list.get(i).getScore());
			res.setReport(list.get(i).getReport());
			res.setRemark(list.get(i).getRemark());
			resList.add(res);
		}
		return resList;
	}

	public List<IndicatorDataDetail> findIndicatorBySchemeId(int schemeId) {
		return resultMapper.findIndicatorBySchemeId(schemeId);
	}

	// 结构化某个方案的指标数据
	public List<IndicatorDetail> buildIndicator(int schemeId) {
		// 查找总分
		SchemeList s = resultMapper.findSchemeById(schemeId);

		List<IndicatorDetail> list = new ArrayList<>();
		// 找到该方案下level2的节点
		List<IndicatorDataDetail> level2 = resultMapper.findLevelTwo(schemeId);
		for (int i = 0; i < level2.size(); i++) {
			IndicatorDataDetail levelTwo = level2.get(i);

			// 找到level3
			List<IndicatorDataDetail> level3 = resultMapper.findLevelThree(schemeId);
			for (int j = 0; j < level3.size(); j++) {
				IndicatorDataDetail levelThree = level3.get(j);
				// 找到对应的指标
				if (levelThree.getIndicatorPath().indexOf(levelTwo.getIndicatorPath()) != -1) {
					IndicatorDetail temp = new IndicatorDetail();
					temp.setLevel2Name(levelTwo.getIndicatorName());
//                    temp.setLevel3Name(levelThree.getIndicatorName());
//                    temp.setLevel2Value(levelTwo.getValue());
//                    temp.setLevel3Value(levelThree.getValue());
					temp.setLevel2Value(
							levelTwo.getEntryValue1() == 0 ? levelTwo.getEntryValue2() : levelTwo.getEntryValue1());
//                    temp.setLevel3Value(levelThree.getEntryValue1()==0?levelThree.getEntryValue2():levelThree.getEntryValue1());
					temp.setLevel3Value(levelThree.getEntryValue1() == 0 ? levelThree.getEntryValue2() : -1);

					temp.setLevel2RelativeWeight(levelTwo.getRelativeWeight());
//                    temp.setLevel3RelativeWeight(levelThree.getRelativeWeight());
					if (levelThree.getRelativeWeight() == 0) {
						temp.setLevel3RelativeWeight(-1);
						temp.setLevel3Name("该指标下无二级指标");
					} else {
						temp.setLevel3RelativeWeight(levelThree.getRelativeWeight());
						temp.setLevel3Name(levelThree.getIndicatorName());
					}
//                    temp.setLevel2EntryValue1(levelTwo.getEntryValue1());
//                    temp.setLevel2EntryValue2(levelTwo.getEntryValue2());
//                    temp.setLevel3EntryValue1(levelThree.getEntryValue1());
//                    temp.setLevel3EntryValue2(levelThree.getEntryValue2());
//                    temp.setLevel2EntryValue(levelTwo.getEntryValue1()==0?levelTwo.getEntryValue2():levelTwo.getEntryValue1());
//                    temp.setLevel3EntryValue(levelThree.getEntryValue1()==0?levelThree.getEntryValue2():levelThree.getEntryValue1());
					temp.setScore(s.getScore());
					list.add(temp);
				}
			}
		}
		return list;
	}

	// 二级指标数据
	public List<Double> findLevelTwoScore(int schemeId) {
		List<Double> list = new ArrayList<>();
		List<IndicatorDataDetail> level2 = resultMapper.findLevelTwo(schemeId);
		for (int i = 0; i < level2.size(); i++) {
			double tempScore = level2.get(i).getEntryValue2();
			list.add(tempScore);
		}
		return list;
	}

	// 一级指标权重饼图
	public List<PieVO> buildPieOne(int schemeId) {
		List<PieVO> list = new ArrayList<>();
		List<IndicatorDataDetail> level2 = resultMapper.findLevelTwo(schemeId);
		for (int i = 0; i < level2.size(); i++) {
			PieVO pie = new PieVO();
			pie.setName(level2.get(i).getIndicatorName());
			pie.setValue(level2.get(i).getRelativeWeight());// 把数据放进去
			list.add(pie);
		}
		return list;
	}

	// 一级指标雷达图指标名称
	public List<Radar> buildRadar(int schemeId) {
		List<Radar> list = new ArrayList<>();
		List<IndicatorDataDetail> level2 = resultMapper.findLevelTwo(schemeId);
		for (int i = 0; i < level2.size(); i++) {
			Radar radar = new Radar();
			radar.setText(level2.get(i).getIndicatorName());
			radar.setMax(100);
			radar.setValue(level2.get(i).getEntryValue2());// 把数据放进去
			list.add(radar);
		}
		return list;
	}

	// 二级指标评分柱状图
	public List<Bar> buildBar(int schemeId, String levelOne) {
		List<Bar> list = new ArrayList<>();
		List<IndicatorDataDetail> level3 = resultMapper.buildBar(schemeId, levelOne);
		for (int i = 0; i < level3.size(); i++) {
			Bar bar = new Bar();
			bar.setName(level3.get(i).getIndicatorName());
			if (level3.get(i).getEntryValue2() != 0) {
				bar.setValue(level3.get(i).getEntryValue2());
			} else {
				bar.setValue(level3.get(i).getEntryValue1());
			}
			list.add(bar);

		}
		return list;
	}

	// 二级指标权重饼状图
	public List<Bar> buildPieTwo(int schemeId, String levelOne) {
		List<Bar> list = new ArrayList<>();
		List<IndicatorDataDetail> level3 = resultMapper.buildBar(schemeId, levelOne);
		for (int i = 0; i < level3.size(); i++) {
			Bar bar = new Bar();// Bar(name,value)
			bar.setName(level3.get(i).getIndicatorName());
			if (level3.get(i).getIndicatorName().contentEquals("分队到位率")) {
				bar.setValue(1.0);
			} else {
				bar.setValue(level3.get(i).getRelativeWeight());
			}

			list.add(bar);
		}
		return list;
	}

	public String deleteScheme(int id) {
		resultMapper.deleteScheme(id);
		resultMapper.deleteSchemeDetail(id);
		return ResponseUtil.getResponseString(ErrorCode.SUCCESSFUL, "successful", "1");
	}

	// 根据用户信息获取任务详情（模拟接口）
	private int getTask(int userId) {
		if (userId == 1) {
			// 主攻任务
			return 11;
		} else if (userId == 2) {
			// 地面攻击任务
			return 21;
		} else if (userId == 3) {
			// 空中突击任务
			return 23;
		} else if (userId == 4) {
			// 空中突击任务
			return 22;
		} else if (userId == 5) {
			// 空中突击任务
			return 24;
		} else if (userId == 6) {
			// 空中突击任务
			return 25;
		} else if (userId == 7) {
			// 空中突击任务
			return 26;
		} else if (userId == 8) {
			// 空中突击任务
			return 27;
		} else if (userId == 9) {
			// 空中突击任务
			return 28;
		} else if (userId == 10) {
			// 空中突击任务
			return 29;
		} else if (userId == 11) {
			// 空中突击任务
			return 30;
		} else {
			return 11;
		}
	}

	// 获取子分队
	public List<Integer> getChlidUnit(int upUserId) {
		int taskId = getTask(upUserId);
		List<Integer> childIds = new ArrayList<>();
		try {
			File f = new File("config/task-" + taskId + ".xml");
			SAXReader reader = new SAXReader();
			Document doc = reader.read(f);
			Element root = doc.getRootElement();
			Element foo;
			// 读取任务列表
			for (Iterator i = root.elementIterator("任务"); i.hasNext();) {
				foo = (Element) i.next();
				Element foo2;
				for (Iterator j = foo.elementIterator("子任务"); j.hasNext();) {
					foo2 = (Element) j.next();
				}
			}
			// 读取部队编成
			for (Iterator i = root.elementIterator("部队编成"); i.hasNext();) {
				foo = (Element) i.next();
				Element foo2;
				for (Iterator j = foo.elementIterator("分队"); j.hasNext();) {
					foo2 = (Element) j.next();
					Element foo3;
					for (Iterator k = foo2.elementIterator("子部队"); k.hasNext();) {
						foo3 = (Element) k.next();
						childIds.add(new Integer(foo3.getText()));
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return childIds;
	}

	// 根据用户信息获取用户级别（模拟接口）
	private int getUserLevel(int userId) {
		if (userId == 1) {
			// 旅一级
			return 1;
		} else {
			// 分队一级
			return 2;
		}
	}

	public String getResultTag1(int schemeId, int userId) {
		EvalResult evalResult = new EvalResult();
		// 找到该方案下level2的节点
		List<IndicatorDataDetail> level2 = resultMapper.findLevelTwo(schemeId);
		for (int i = 0; i < level2.size(); i++) {
			IndicatorDataDetail levelTwo = level2.get(i);
			// 顺便构建评估结果：任务完成度、战果、战损
			if (levelTwo.getIndicatorName().equals("任务完成度")) {
				evalResult.setCompletion(
						levelTwo.getEntryValue1() == 0 ? levelTwo.getEntryValue2() : levelTwo.getEntryValue1());
			}
			if (levelTwo.getIndicatorName().equals("我方战果")) {
				evalResult.setConquest(
						levelTwo.getEntryValue1() == 0 ? levelTwo.getEntryValue2() : levelTwo.getEntryValue1());
			}
			if (levelTwo.getIndicatorName().equals("我方战损")) {
				evalResult.setDamage(
						levelTwo.getEntryValue1() == 0 ? levelTwo.getEntryValue2() : levelTwo.getEntryValue1());
			}
		}

		String[] deviateArray = resultMapper.getDeviate(schemeId).split("/");
		List<String> deviateList = Arrays.asList(deviateArray);
		List<String> solveDeviate = new ArrayList<String>();
		setSolveMap();
		getDivateMap();
		for (String deviate : deviateList) {
			solveDeviate.add("\"" + deviate + "\"：" + this.divateMap.get(deviate) + "，" + this.solveMap.get(deviate));
		}

		evalResult.setSolveDivate(solveDeviate);
		// 获取分队得分
		List<Integer> childrenIds = getChlidUnit(userId);
		if (!childrenIds.isEmpty()) {
			List<SchemeList> cScores = new ArrayList<SchemeList>();
			for (int cid : childrenIds) {
				int cUserLevel = getUserLevel(cid);
				int cTaskId = getTask(cid);
				int cIndicatorId = evalDataEnterMapper.getNowIndicatorId(cUserLevel, cTaskId);
				SchemeList cScheme = evalDataEnterMapper.getChildScore(cIndicatorId);
				cScores.add(cScheme);
			}
			evalResult.setChildrenScheme(cScores);
		}
		this.divateMap.clear();
		this.solveMap.clear();
		return ResponseUtil.getResponseString(ErrorCode.SUCCESSFUL, "successful", evalResult);
	}

	private void getDivateMap() {
		this.divateMap.put("任务完成度", "严重落后作战计划");
		this.divateMap.put("目标敌人员伤亡情况", "目标敌人员杀伤较低");
		this.divateMap.put("目标敌装备毁伤情况", "目标敌装备毁伤过低");
		this.divateMap.put("目标敌关键目标摧毁情况", "目标敌设施尚未摧毁");
		this.divateMap.put("敌方区域攻占", "目标敌区域尚未攻占");
		this.divateMap.put("本单位人员伤亡情况", "我方人员伤亡过高");
		this.divateMap.put("本单位装备毁伤情况", "我方装备毁伤过高");
		this.divateMap.put("本单位关键目标被摧毁情况", "我方设施被摧毁严重");
		this.divateMap.put("我方区域失去", "我方区域被攻占");
		this.divateMap.put("战斗部署", "各部队到位滞后");
		this.divateMap.put("是否及时", "临机处置不够及时");
		this.divateMap.put("是否正确", "临机处置不够得当");
		this.divateMap.put("战斗协同", "各部队协同作战效果不良");
	}

	private void setSolveMap() {
		this.solveMap.put("任务完成度", "加速推进任务进程");
		this.solveMap.put("目标敌人员伤亡情况", "增强搜索目标敌人员动向并杀伤");
		this.solveMap.put("目标敌装备毁伤情况", "加强侦察目标敌装备位置并摧毁");
		this.solveMap.put("目标敌关键目标摧毁情况", "尽快向目标敌设施发起进攻");
		this.solveMap.put("敌方区域攻占", "尽快向目标敌区域发起进攻");
		this.solveMap.put("本单位人员伤亡情况", "请求增补作战人员");
		this.solveMap.put("本单位装备毁伤情况", "请求增强主战装备");
		this.solveMap.put("本单位关键目标被摧毁情况", "请求增援维修设施或新建临时设施");
		this.solveMap.put("我方区域失去", "请求增援夺回被攻占区域");
		this.solveMap.put("战斗部署", "督促未到位部队尽快完成部署");
		this.solveMap.put("是否及时", "缩短临机处置时间");
		this.solveMap.put("是否正确", "调整临机处置方案");
		this.solveMap.put("战斗协同", "对相关责任的部队督促整改");
	}
}